package com.ruoyi.framework.manager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.stream.Stream;

/**
 * @author kong
 */
@Component
public class TomcatCacheCleaner implements WebServerFactoryCustomizer<TomcatServletWebServerFactory>
{

    private static final Logger log = LoggerFactory.getLogger(TomcatCacheCleaner.class);

    @Value("${server.tomcat.basedir}")
    private String baseDir;


    @Override
    public void customize(TomcatServletWebServerFactory factory)
    {
        Path path = Paths.get(this.baseDir);
        if (Files.exists(path))
        {
            try (Stream<Path> stream = Files.walk(path))
            {
                // 删除目录及其内容
                stream.sorted(Comparator.reverseOrder())
                        .map(Path::toFile)
                        .forEach(File::delete);
            }
            catch (Exception e)
            {
                log.error("Failed to clean tomcat cache:{}", e.getMessage(), e);
            }
        }
    }
}